package com.vxdata.utils.modules.utils.equipment;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 对比两个对象的字段数据有没有不同的
 * 通过注解, 标注要对比的字段
 */
public class BeanUtils {

    /**
     * 获取变更内容
     *
     * @param newBean 更改前的Bean
     * @param oldBean 更改后的Bean
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> getChangedFields(T newBean, T oldBean) {
        Field[] fields = newBean.getClass().getDeclaredFields();
        StringBuilder editField = new StringBuilder();
        StringBuilder editContent = new StringBuilder();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(ForUpdate.class)) {
                try {
                    Object newValue = field.get(newBean);
                    Object oldValue = field.get(oldBean);
                    if (!Objects.equals(newValue, oldValue)) {
                        Class<?> type = field.getType();
                        // 获取被更改的字段
                        if (editField.length() > 0) {
                            editField.append(",");
                            editField.append(field.getName());
                        } else {
                            editField.append(field.getName());
                        }

                        //获取字段中文名称
                        String fieldName = field.getAnnotation(ForUpdate.class).fieldName();
                        editContent.append(fieldName);
                        if (!fieldName.equals("图片")) {
                            editContent.append(":[");
                            editContent.append(oldValue);
                            editContent.append("—>");
                            editContent.append(newValue);
                            editContent.append("]");
                        }
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("editField", editField.toString());
        map.put("editContent", editContent.toString());
        return map;
    }

    public static void main(String[] args) {
        TestBean bean1 = new TestBean("张三", "18", "男", "13888888888");
        TestBean bean2 = new TestBean("李四", "18", "男", "13888888888");
        Map<String, String> changedFields = getChangedFields(bean1, bean2);
        System.out.println(changedFields);
    }


    @Data
    @AllArgsConstructor
    private static class TestBean {
        @ForUpdate(fieldName = "名称")
        private String name;
        @ForUpdate(fieldName = "年龄")
        private String age;
        @ForUpdate(fieldName = "性别")
        private String sex;
        @ForUpdate(fieldName = "手机号")
        private String phone;
    }
}
